package com.smalljj.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.smalljj.comm.ActivityStackControlUtil;
import com.smalljj.comm.Constants;
import com.smalljj.comm.LocationApplicationBean;
import com.smalljj.comm.Util;

public class MainActivity extends Activity {
	
	private SharedPreferences sp;

	// 为文字定一个数组
	private String[] texts = { "当前位置", "旧日足迹", "迹游记载",  "我的迹友", "周边资讯","什么菜单",  "透明中心", "系统设置", "关于迹迹" };
	// 为图片定义一个数组
	private Integer[] images = { R.drawable.menu0, R.drawable.menu1, R.drawable.menu2, 
								R.drawable.menu3, R.drawable.menu4, R.drawable.menu5 ,
								R.drawable.menu6, R.drawable.menu7, R.drawable.menu8 };
	
	private static int[] foot_img = { R.drawable.background, R.drawable.close };  
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除标题
		setContentView(R.layout.main);
		ActivityStackControlUtil.add(this);
		
		Log.i(Constants.LOG_TAG, "生成九宫格菜单开始...");
		//生成九宫格菜单
		GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(new ImageAdapter(this));
		gridview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long id) {
				switch (index) {
				case 0:
					startActivity(new Intent(MainActivity.this, NowMeActivity.class));
					finish();
					break;
				case 1:
					break;
				case 2:
					break;
				case 3:
					startActivity(new Intent(MainActivity.this, FriendActivity.class));
					finish();
					break;
				case 4:
					break;
				case 5:
					break;
				case 6:
					break;
				case 7:
					break;
				case 8:
					break;
				}
			}
		});
		Log.i(Constants.LOG_TAG, "生成底部菜单结束!");
		
		Log.i(Constants.LOG_TAG, "生成底部菜单开始...");
		//底部菜单
		GridView grid_foot_view = (GridView) findViewById(R.id.grid_footv_view); 
		ArrayList<HashMap<String,Object>> menu_data = new ArrayList<HashMap<String,Object>>();  
        for(int i=0;i<foot_img.length;i++){  
            HashMap<String,Object> map = new HashMap<String, Object>();  
            map.put("menu_foot_image", foot_img[i]);
            menu_data.add(map);  
        }
        //向菜单栏中的控件添加适配其 
        SimpleAdapter adapter = new SimpleAdapter(this, menu_data, R.layout.menu_foot_item, 
        		new String[]{"menu_foot_image"}, new int[]{R.id.item_foot_iamge});  
        grid_foot_view.setAdapter(adapter);  
        grid_foot_view.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long id) {
				switch (index) {
				case 0:
					Intent intent = new Intent(Intent.ACTION_MAIN);  
					intent.addCategory(Intent.CATEGORY_HOME);  
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
					startActivity(intent);  
					break;
				case 1:
					new AlertDialog.Builder(MainActivity.this)
					.setTitle("退出")
					.setMessage("完全退出后，将失去记录行走轨迹的功能，你确定吗?")
					.setPositiveButton("后台运行", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();// 关闭对话框
							Intent intent = new Intent(Intent.ACTION_MAIN);  
							intent.addCategory(Intent.CATEGORY_HOME);  
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
							startActivity(intent);  
						}
					}).setNegativeButton("退出", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							//关闭定位
							((LocationApplicationBean)getApplication()).closeLocationTask();
							ActivityStackControlUtil.finishProgram();
						}
					}).create().show();
				}
			}
		});
		Log.i(Constants.LOG_TAG, "生成底部菜单结束!");

		Log.i(Constants.LOG_TAG, "检查网络开始...");
		// 获取系统的连接服务
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		// 无网络
		if (connectivity.getActiveNetworkInfo() == null) {
			noNetworkDialog();
			return;
		} else {
			NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
			if (networkInfo == null || networkInfo.isAvailable() == false) {
				noNetworkDialog();
				return;
			}
		}
		Log.i(Constants.LOG_TAG, "检查网络结束!");

		Log.i(Constants.LOG_TAG, "检查新版本开始...");
		// 检查新版本
		CheckVersionTask checkVersionTask = new CheckVersionTask();
		checkVersionTask.execute();
		Log.i(Constants.LOG_TAG, "检查新版本结束!");

		Log.i(Constants.LOG_TAG, "尝试开启定位...");
		//开启定位
		((LocationApplicationBean)getApplication()).openLocationTask();
		Log.i(Constants.LOG_TAG, "开启定位成功!");

		Log.i(Constants.LOG_TAG, "打开存储实例...");
		// 获得SharedPreferences实例对象
		sp = this.getSharedPreferences(Constants.SharedPreferencesName, Context.MODE_PRIVATE);//不用MODE_WORLD_READABLE
		Log.i(Constants.LOG_TAG, "成功打开存储实例!");
	}

	/**
	 * 无网络
	 */
	private void noNetworkDialog() {
		Dialog dialog = new AlertDialog.Builder(MainActivity.this)
			.setTitle("注意").setMessage("当前网络不可用,请检查网络!")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();// 关闭对话框
					ActivityStackControlUtil.finishProgram();
				}
			}).create();
		dialog.show();
	}

	/**
	 * 新版本
	 */
	private void newVersionDialog(final String newVersion) {
		new AlertDialog.Builder(MainActivity.this)
		.setTitle("提示")
		.setMessage("检测到新版本,建议更新使用!")
		.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();// 关闭对话框
				// 切换到更新activity
				Bundle bundle = new Bundle();
				bundle.putString("newVersion", newVersion);// 把这个版本号传到UpdateActivity
				Intent intent = new Intent(MainActivity.this,UpdateActivity.class);
				intent.putExtras(bundle);
				MainActivity.this.startActivity(intent);
				MainActivity.this.finish();
			}
		}).setNegativeButton("忽略", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).create().show();
	}

	/**
	 * 检测版本更新
	 * 
	 */
	class CheckVersionTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			return Util.checkNewVersion();
		}

		@Override
		protected void onPostExecute(String result) {
			if (result.equals("") == false) {
				newVersionDialog(result);
				return;
			}
		}
	}

	// 为自定义主界面而配的适配器
	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
		}

		// 返回图片的长度
		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object getItem(int index) {
			return null;
		}

		@Override
		public long getItemId(int index) {
			return 0;
		}

		@Override
		public View getView(int index, View convertView, ViewGroup parent) {
			View view;
			LayoutInflater li = getLayoutInflater();
			view = li.inflate(R.layout.main_textview, null);
			ImageView image = (ImageView) view.findViewById(R.id.main_images);
			image.setPadding(5, 5, 5, 5);// 图片之间的距离
			image.setAdjustViewBounds(true);// 边界是否对齐
			image.setImageResource(images[index]);
			TextView menu_title = (TextView) view.findViewById(R.id.main_text);
			menu_title.setText(texts[index]);
			return view;
		}
	}
	/**
	 * 返回按钮的控制
	 */
	/*
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		PackageManager pm = getPackageManager();
		ResolveInfo homeInfo = 
				pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);  
		if (keyCode == KeyEvent.KEYCODE_BACK) {
	        ActivityInfo ai = homeInfo.activityInfo;
	        Intent startIntent = new Intent(Intent.ACTION_MAIN);
	        startIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
	        startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
	        startActivitySafely(startIntent);
	        return true;  
	    } else {
	        return super.onKeyDown(keyCode, event);
	    }
	}*/
	
	void startActivitySafely(Intent intent) {
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    try {
	        startActivity(intent);
	    } catch (ActivityNotFoundException e) {  
            Toast.makeText(this, "null",Toast.LENGTH_SHORT).show();  
        } catch (SecurityException e) {  
            Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();   
        } 
	}  
	
	@Override
	protected void onDestroy() { 
        super.onDestroy();
        //移出管理栈
        ActivityStackControlUtil.remove(this); 
	} 
}